<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

</head>

<body>
    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            top: 0;
            left: 0
        }
    </style>
    <div></div>
</body>

</html>
<script src="../common.js"></script>
<script>
    //思路
    //1、绑定鼠标的按下事件
    //2、绑定鼠标移动事件 鼠标移动过程中让div跟着移动
    //3、绑定鼠标的抬起事件
    let div = $$('div');

    function handler(event) {

        let x = event.pageX - div.clientWidth / 2;
        let y = event.pageY - div.clientHeight / 2;
        //需要保证坐标点在中间
        div.style.top = y + 'px';
        div.style.left = x + 'px';
        console.log('move');
    }
    div.addEventListener('mousedown', function () {
        //移动在按下之内
        div.addEventListener('mousemove', handler)
    })

    div.addEventListener('mouseup', function () {
        //抬起时移动要失效
        div.removeEventListener('mousemove', handler)
    })
</script>